package com.xianyun.smartpicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xianyun.smartpicturebackend.constant.UserConstant;
import com.xianyun.smartpicturebackend.exception.BusinessException;
import com.xianyun.smartpicturebackend.exception.ErrorCode;
import com.xianyun.smartpicturebackend.exception.ThrowUtils;
import com.xianyun.smartpicturebackend.mapper.UserMapper;
import com.xianyun.smartpicturebackend.model.dto.user.UserQueryRequest;
import com.xianyun.smartpicturebackend.model.dto.user.UserRegisterRequest;
import com.xianyun.smartpicturebackend.model.entity.User;
import com.xianyun.smartpicturebackend.model.enums.UserRoleEnum;
import com.xianyun.smartpicturebackend.model.vo.UserLoginVO;
import com.xianyun.smartpicturebackend.model.vo.UserVO;
import com.xianyun.smartpicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jxm12
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-02-12 22:15:23
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @Override
    public long userRegister(UserRegisterRequest userRegisterRequest) {
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        //1. 校验参数
        if (StrUtil.hasBlank(userRegisterRequest.getUserAccount(), userRegisterRequest.getUserPassword(),
                userRegisterRequest.getCheckPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        if (userRegisterRequest.getUserAccount().length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        //2. 校验用户账户是否和数据库中的重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userRegisterRequest.getUserAccount());
        Long count = this.baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名重复");
        }
        //3. 密码加密
        String encryptPassword = getEncryptPassword(userPassword);
        //4. 插入数据到数据库中
        User user = new User();
        user.setUserAccount(userRegisterRequest.getUserAccount());
        user.setUserPassword(encryptPassword);
        user.setUserName("默认名称");
        user.setUserRole(UserRoleEnum.USER.getValue());
        boolean save = this.save(user);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败");
        }
        return user.getId();
    }

    /**
     * 用户登录
     * LoginUserVO 封装脱敏后的用户信息
     *
     * @param userAccount
     * @param userPassword
     * @param request
     * @return
     */
    @Override
    public UserLoginVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1. 校验参数
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword), ErrorCode.PARAMS_ERROR, "参数不能为空");
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名长度最短为4");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码长度最短为8");
        }
        //2. 根据参数去数据库查询有没有对应的用户？继续登录 ：抛异常
        //   （注意此时的密码应该调用加密方法加密后再去数据库查询）
        String encryptPassword = getEncryptPassword(userPassword);
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("userAccount", userAccount);
        qw.eq("userPassword", encryptPassword);
        User user = this.baseMapper.selectOne(qw);
        if (user == null) {
            //记录日志最好用英文，占用空间小
            log.info("user login failed, userAccount or userPassword cannot match database");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名或密码错误");
        }
        //3. 登录成功，保存登录状态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        return this.getLoginUserVO(user);
    }

    /**
     * 获取当前登录用户，后台内不调用，所以返回类型直接是 User
     *
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        //调用自定义工具类，判断用户是否登录
        ThrowUtils.throwIf(currentUser == null ||
                currentUser.getId() == null, ErrorCode.NOT_LOGIN_ERROR);
        //建议：应该从数据库中再差一遍，避免 Session 中缓存不一致的情况
        Long userId = currentUser.getId();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("id", userId);
        currentUser = this.baseMapper.selectOne(userQueryWrapper);
        //从数据库中查出来，如果为空，则抛出异常（用户干了不合法的事，被管理员删除）
        if (currentUser == null) {
            new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户已被删除");
        }
        return currentUser;
    }

    /**
     * 用户登录态注销
     *
     * @param request
     * @return
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        //1. 用户是否已经登录
        User currentUser = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        ThrowUtils.throwIf(currentUser == null ||
                currentUser.getId() == null, ErrorCode.OPERATION_ERROR, "未登录");

        //2. 从 Session（缓存）中移除登录
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }


    /**
     * 利用SpringBoot提供的DigestUtils工具进行加密
     *
     * @param uerPassword
     * @return
     */
    @Override
    public String getEncryptPassword(String uerPassword) {
        //加盐，混淆密码
        final String SALT = "xianyun";

        return DigestUtils.md5DigestAsHex((SALT + uerPassword).getBytes());
    }

    /**
     * 将用户信息脱敏
     *
     * @param user
     * @return 脱敏后的用户信息
     */
    @Override
    public UserLoginVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserLoginVO userLoginVO = new UserLoginVO();
        //利用BeanUtil工具类进行属性拷贝，将user中的属性拷贝到loginUserVO中
        BeanUtil.copyProperties(user, userLoginVO);
        return userLoginVO;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        //利用BeanUtil工具类进行属性拷贝，将user中的属性拷贝到loginUserVO中
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 获取脱敏后的用户列表
     * @param userList
     * @return
     */
    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();//如果为空，返回空数组
        }

        return userList.stream()
                .map(this::getUserVO)
                .collect(Collectors.toList());
    }

    /**
     * 获取查询条件
     * @param userQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        /*
        这样包装查询条件，实现了代码解耦，用户传来什么参数我们就根据什么参数构建对象，
        没有传来的参数，就不构建这个参数（通过NotNull实现控制）
         */
        String id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        //ascend 表升序，descend 降序
        queryWrapper.orderBy(StrUtil.isNotBlank(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }


}




